from datetime import datetime

from fastapi import APIRouter, Depends
from fastapi_pagination import Page
from sqlalchemy import desc
from sqlalchemy.orm import Session
from fastapi_pagination.ext.sqlalchemy import paginate
from backend.common.database import get_db
from backend.models.notice import Notice
from backend.schemas.notice import NoticeSchema, ResNoticeSchema

notice = APIRouter()


@notice.get("/all", summary="获取公告", response_model=Page[ResNoticeSchema])
async def get_all_notice(db: Session = Depends(get_db)):
    notices = db.query(Notice).order_by(Notice.id.desc())
    paginated_notices = paginate(notices)
    return paginated_notices


@notice.get("/{notice_id}", summary="获取指定公告详情")
async def get_notice(notice_id: int, db: Session = Depends(get_db)):
    db_notice = db.query(Notice).filter(Notice.id == notice_id).first()
    notice_dict = db_notice.to_dict()
    return notice_dict


@notice.post("/", summary="增加公告")
async def post_notice(data: NoticeSchema, db: Session = Depends(get_db)):
    db_notice = Notice(content=data.content, status=data.status, publish_time=data.publish_time)
    db.add(db_notice)
    db.commit()
    db.refresh(db_notice)
    return {"msg": "success"}


@notice.put("/{notice_id}", summary="修改公告")
async def put_notice(notice_id: int, data: NoticeSchema, db: Session = Depends(get_db)):
    db_notice = db.query(Notice).filter(Notice.id == notice_id).first()
    db_notice.content = data.content
    db_notice.status = data.status
    db.commit()
    db.refresh(db_notice)
    return {"msg": "success"}


@notice.post('/publish/{notice_id}', summary="发布公告")
async def publish_notice(notice_id: int, db: Session = Depends(get_db)):
    db_notice = db.query(Notice).filter(Notice.id == notice_id).first()
    db_notice.publish_time = datetime.now()
    db_notice.status = 1
    db.commit()
    db.refresh(db_notice)
    return {"msg": "success"}


@notice.delete("/{notice_id}", summary="删除公告")
async def delete_notice(notice_id: int, db: Session = Depends(get_db)):
    db_notice = db.query(Notice).filter(Notice.id == notice_id).first()
    db_notice.is_delete = 1
    db.commit()
    db.refresh(db_notice)
    return {"msg": "success"}





